package com.example.zzy.zzytest.data.structure.stack.polandnotation;


/**
 * 逆波兰计算
 */
public class PolandNotation {
    public static void main(String[] args) {
        String calcText = "1+((2+3)*4)-5";
        String polandText = PolandConverse.converse(PolandConverse.toInfixExpList(calcText));
        char[] chars = polandText.toCharArray();
        CalcArrayStack stack = new CalcArrayStack(10);
        int c1, c2, res;

        for (char c : chars) {
            if (isOp(c)) {
                c1 = stack.popStack();
                c2 = stack.popStack();
                res = calc(c1, c2, c);
                stack.pushStack(res);
            } else {
                stack.pushStack(Character.getNumericValue(c));
            }
        }

        System.out.println(stack.popStack());
    }

    public static int calc(int num1, int num2, int op) {
        if (op == '+') return num1 + num2;
        if (op == '-') return num2 - num1;
        if (op == '*') return num1 * num2;
        if (op == '/') return num2 / num1;
        else return Integer.MIN_VALUE;
    }

    public static boolean isOp(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }

    public static int priority(int c) {
        if (c == '*' || c == '/') {
            return 1;
        } else if (c == '+' || c == '-') {
            return 0;
        } else {
            return -1;
        }
    }
}

class CalcArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public CalcArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
    }

    //看栈顶
    public int peek() {
        if (!isEmpty()) {
            return this.stack[top];
        } else {
            System.out.println("栈为空");
            return Integer.MIN_VALUE;
        }

    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //栈空
    public boolean isEmpty() {
        return top == -1;
    }

    //入栈
    public void pushStack(int num) {
        if (isFull()) {
            System.out.println("栈已满，入栈失败");
            return;
        }
        top++;
        this.stack[top] = num;
    }

    //出栈
    public int popStack() {
        if (isEmpty()) {
            System.out.println("栈为空，出栈失败");
            return Integer.MIN_VALUE;
        }
        int num = this.stack[top--];
        return num;
    }

    //遍历
    public void list() {
        for (int i = top; i >= 0; i--) {
            System.out.println(this.stack[i] + "\t");
        }
    }
}
